import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Random;
import java.util.Scanner;

/**
 * 四则运算
 */
public class MathQuizGenerator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请选择年级（一、二、三）：");
        String grade = scanner.nextLine();

        System.out.println("请输入题目数量：");
        int numOfQuestions = Integer.parseInt(scanner.nextLine());

        generateMathQuizzes(grade, numOfQuestions);

        scanner.close();
    }

    private static void generateMathQuizzes(String grade, int numOfQuestions) {
        Random random = new Random();

        for (int i = 0; i < numOfQuestions; i++) {
            int operand1 = random.nextInt(100) + 1;
            int operand2 = random.nextInt(100) + 1;

            // 根据年级选择运算符和答案限制
            char operator1, operator2;
            int answer;
            if ("一".equals(grade)) {
                operator1 = '+';
                operator2 = '-';
                do {
                    answer = evaluate(operand1, operand2, operator1, operator2);
                } while (answer < 0 || answer > 100); // 限制答案在 0 到 100 之间
            } else if ("二".equals(grade)) {
                operator1 = '+';
                operator2 = '+';
                answer = operand1 + operand2;
            } else if ("三".equals(grade)) {
                do {
                    operator1 = getRandomOperator();
                    operator2 = getRandomOperator();
                    answer = evaluate(operand1, operand2, operator1, operator2);
                } while (answer < 0 || answer > 100); // 限制答案在 0 到 100 之间
            } else {
                System.out.println("不支持的年级选择");
                return;
            }

            String question = String.format("%d %c %d %c %d", operand1, operator1, operand2, operator2, getRandomOperand());

            System.out.println(question + " = " + answer);
        }
    }

    private static char getRandomOperator() {
        char[] operators = {'+', '-', '*'};
        Random random = new Random();
        return operators[random.nextInt(operators.length)];
    }

    private static int getRandomOperand() {
        Random random = new Random();
        return random.nextInt(100) + 1;
    }

    private static int evaluate(int operand1, int operand2, char operator1, char operator2) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");

        String expression = String.format("%d %c %d %c %d", operand1, operator1, operand2, operator2, getRandomOperand());

        try {
            // 使用 JavaScript 引擎计算表达式
            return (int) engine.eval(expression);
        } catch (ScriptException e) {
            // 如果出现异常，返回一个不可能的值
            return -1;
        }
    }
}
